<?php

namespace addons\facrm\controller\facrm\business;

use addons\facrm\library\BackendApi;

use think\Db;
use think\Exception;
use think\exception\PDOException;


/**
 * 商机跟进记录
 */
class Record extends BackendApi
{

    protected $model = null;
    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'content';
    protected $childrenAdminIds = [];
    private $types = "business";

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('\app\admin\model\facrm\Record');
        $this->request->filter(['strip_tags']);
    }

    /**
     * [商机]跟进记录
     * @ApiParams(name="business_id", type="int", required=flase, description="商机ID")
     */
    public function index()
    {
        $business_id = $this->request->request("business_id");

        $scene = model('\app\admin\model\facrm\Scene');
        $scene_list = $scene->where('types', 'contacts')
            ->where(function ($query) {
                $query->where('admin_id', 0)->whereor('admin_id', $this->auth->id);
            })
            ->column('id,name');
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_w = [];


        if ($business_id) {
            $filter_w['types_id'] = $business_id;
            //判断是否有该客户的权限
            if (!$this->auth->checkBusinessAuth($business_id, $this->auth)) {
                $this->error(__('您没有权限'));
            }
        }else{
            $filter_w['create_user_id'] = $this->auth->id;
            if (isset($filter['scene_id'])) {
                if (!isset($scene_list[$filter['scene_id']])) {
                    $this->error(__("您没有权限"));
                }
                $filter_w['create_user_id'] = $this->auth->id;
                switch ($filter['scene_id']) {
                    case 4:
                        //全部 超级管理员不做限制
                        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
                        $filter_w['create_user_id'] = ['in', $this->childrenAdminIds];
                        break;
                    case 5:
                        //我的
                        $filter_w['create_user_id'] = $this->auth->id;
                        break;
                    case 6:
                        //下属
                        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(false);
                        $filter_w['create_user_id'] = ['in', $this->childrenAdminIds];
                        break;
                    default://其它的还做TODO
                        $filter_w['create_user_id'] = $this->auth->id;

                }
            }
        }
        unset($filter['scene_id']);
        $this->request->get(['filter' => json_encode($filter)]);
        $filter_w['types'] = $this->types;

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $list = $this->model
            ->where($filter_w)
            ->where($where)
            ->with([
                'createUser' => function ($user) {
                    $user->field('id,username,nickname');
                },
                'business' => function ($business) {
                    $business->field('id,name');
                },
                'files' => function ($files) {
                    $files->field('id,url,record_id');
                },
            ])
            ->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();
        $lists = array();
        foreach ($list as $row) {
            $record_type_text = $row->record_type_text;
            $lists[] = array_merge($row->toArray(), ['record_type_text' => $record_type_text]);//获取器失效
        }
        $result = array("rows" => $lists);


        return $this->success('', $result);


    }

    /**
     * [商机]添加跟进
     * @ApiParams(name="business_id", type="int", required=true, description="商机ID")
     * @ApiParams(name="content", type="string", required=true, description="跟进内容")
     * @ApiParams(name="next_time", type="string", required=flase, description="下次跟进时间")
     * @ApiParams(name="image", type="string", required=flase, description="附件")
     * @ApiParams(name="record_type", type="int", required=true, description="跟进类型")
     * @return mixed
     */
    public function add()
    {
        $business_id = $this->request->request("business_id");
        $business = model('\app\admin\model\facrm\Business');
        $row = $business->get($business_id);
        if (!$row)
            $this->error(__('No Results were found'));
        if (!$this->auth->checkBusinessAuth($row, $this->auth)) {
            $this->error(__('您没有权限:'));
        }
        if (!$this->auth->checkCustomerAuth($row->customer, $this->auth)) {
            $this->error(__('您没有权限:客户权限'));
        }
        $params = $this->request->post();
        Db::startTrans();
        try {
            $params['next_time'] = isset($params['next_time']) && $params['next_time'] ? strtotime($params['next_time']) : 0;
            $params = array_merge($params, [
                'create_user_id' => $this->auth->id,
                'types_id' => $row->id,
                'types' => $this->types,
            ]);
            //更新客户表
            $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
            $result = $this->model->allowField(true)->validateFailException(true)->validate($name . '.add')->save($params);
            if ($result) {
                $row->next_time = $params['next_time'];
                $row->customer()->update(["follow_time" => time()]);
                $row->save();
                //如果存在附件
                if (!empty($params['image'])) {
                    $images = explode(",", $params['image']);
                    $files_data = array();
                    foreach ($images as $key => $v) {
                        $files_data[$key]['url'] = $v;
                        $files_data[$key]['types_id'] = $row->id;
                        $files_data[$key]['types'] = $this->types;
                    }
                    $this->model->files()->saveAll($files_data);
                }
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error(__('添加错误：' . $e->getMessage()));
        }

        return $this->success(__('跟进成功'));
    }

    /**
     * 删除
     * @param string $ids
     */
    public function del()
    {
        $ids = $this->request->request("ids");
        if ($ids) {
            $pk = $this->model->getPk();

            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            $list = $this->model->where($pk, 'in', $ids)->where('create_user_id', 'in', $this->childrenAdminIds)->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success(__("删除成功"));
            } else {
                $this->error(__('没有删除任何数据'));
            }
        }
        $this->error(__('参数 %s 不能为空', 'ids'));
    }

}
